import { Inject, Injectable } from '@nestjs/common';
import { QueryTypes, Op } from 'sequelize';
import sequelize from '../../database/sequelize';
import { Sequelize } from 'sequelize-typescript';
import { encryptPassword, makeSalt } from '../../utils/cryptogram';
import { User, userProvidersName } from '../../database/models/user.entity';

@Injectable()
export class UserService {
  constructor(
    private readonly sequelize: Sequelize,
    @Inject(userProvidersName)
    private readonly usersRepository: typeof User,
  ) {}
  async findOne(account: string | number): Promise<any | undefined> {
    const sql = `SELECT * FROM t_user WHERE account = '${account}'`;
    try {
      const res = await sequelize.query(sql, {
        type: QueryTypes.SELECT,
        raw: true,
        logging: true,
      });
      const user = res[0];
      if (user) {
        return {
          code: 200,
          data: {
            ...user,
          },
          msg: '查询成功',
        };
      } else {
        return {
          code: 206,
          msg: '暂无改用户信息',
        };
      }
    } catch (error) {
      return {
        code: 503,
        msg: `Service error: ${error}`,
      };
    }
  }
  /**
   * 查询是否有该用户
   * @param account 登录账号
   */
  async isUser(account: string): Promise<any | undefined> {
    const sql = `SELECT id, account, password, salt, role FROM t_user WHERE account = '${account}'`;
    try {
      const user = (
        await sequelize.query(sql, {
          type: QueryTypes.SELECT, // 查询方式
          raw: true, // 是否使用数组组装的方式展示结果
          logging: true, // 是否将 SQL 语句打印到控制台
        })
      )[0];
      // 若查不到用户，则 user === undefined
      return user;
    } catch (error) {
      console.error(error);
      return void 0;
    }
  }
  /**
   * 注册
   * @param requestBody 请求体
   */
  async register(requestBody: any) {
    const { account, password, repassword } = requestBody;
    if (password !== repassword) {
      return {
        code: 400,
        msg: '两次密码输入不一致',
      };
    }
    const user = await this.isUser(account);
    if (user) {
      return {
        code: 400,
        msg: '用户已存在',
      };
    }
    const salt = makeSalt();
    const hasPwd = encryptPassword(password, salt);
    try {
      const userRes = await this.usersRepository.create({
        ...requestBody,
        password: hasPwd,
        salt,
      });
      return {
        code: 200,
        data: userRes,
        msg: 'Success',
      };
    } catch (error) {
      return {
        code: 503,
        msg: `Service error: ${error}`,
      };
    }
  }
}
